package com.shj.em.generator;

import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MyTemplateEngine extends FreemarkerTemplateEngine {

    public Map<String, Object> getObjectMap(TableInfo tableInfo) {
        Map<String, Object> map = super.getObjectMap(tableInfo);
        map.put("entityLowerName", StringUtils.lowerCase(tableInfo.getEntityName()));
        map.put("hasDecimalField", false);
        map.put("hasDateField", false);

        List<TableField> editFields = new ArrayList<>();
        for(TableField field : tableInfo.getFields()){
            if(field.isKeyFlag() || field.isKeyIdentityFlag()){
                map.put("pkColName", field.getPropertyName());
                map.put("pkTblColName", field.getName());
                map.put("pkColType", field.getPropertyType());
            }else{
                if(!isFieldInSuperEntity(field.getPropertyName())){
                    editFields.add(field);
                }
            }
            if("Date".equalsIgnoreCase(field.getPropertyType())){
                map.put("hasDateField", true);
            }
            if("BigDecimal".equalsIgnoreCase(field.getPropertyType())){
                map.put("hasDecimalField", true);
            }
        }
        map.put("editFields", editFields);

        return map;
    }

    private boolean isFieldInSuperEntity(String fieldName){
        for(String name : DataConstant.DEFAULT_AUDIT_FIELDS_NAME){
            if(name.equalsIgnoreCase(fieldName)){
                return true;
            }
        }
        return false;
    }
}
